<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">点我</button>
    <script>
        // 防抖
        // 简化版本：
        var debounce = function (fn, delay){
            let timer = null;
            return function (){
                clearTimeout(timer);
                timer = setTimeout(function(){
                    fn.apply(this);
                }, delay)
            }
        }
        // 带参数版本：
        var debounceArg = function (fn, delay){
            var timer = null;
            return function(){
                let context = this;
                let args = arguments;
                if(timer){
                    clearTimeout(timer);
                }
                timer = setTimeout(function(){
                    fn.apply(context, args);
                }, delay);
            }
        }
        
        // 节流
        // 时间戳版本(简化)：
        var throttle = function(fn,delay) {
            var lastTime = 0;
            return function(){
                var nowTime = Date.now();
                if(nowTime-lastTime>delay){
                    fn.call(this);
                    lastTime = nowTime;
                }
            }
        }
        // 时间戳版本（带参数）：
        var throttle = function(fn,delay) {
            let last = 0;
            return function(){
                let cur = Date.now();
                let context = this;
                let args = arguments;
                if(cur-last>delay){
                    fn.apply(context, args);
                    last = cur;
                }
            }
        }
        // 定时器版本
        var throttleTime = function (func, wait){
            let timeout;
            return function() {
                let context = this;
                let args = arguments;
                if (!timeout) {
                    timeout = setTimeout(() => {
                        timeout = null;
                        func.apply(context, args)
                    }, wait)
                }

            }
        }

        let count = 0;
        function add(){
            console.log('click me: ', count++);
        }

        var btn = document.getElementById('btn');
        btn.onclick = debounce(add, 1000);
        // btn.onclick = throttle(function(){console.log('click me')}, 2000);

        // 函数柯里化
        Function.prototype.bind = function (context) {
            var _this = this
            var args = Array.prototype.slice.call(arguments, 1)
        
            return function() {
                return _this.apply(context, args)
            }
        }
    </script>
</body>
</html>